package com.bbc.base.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.bbc.util.CookiesUtils;
import com.bbc.util.PwdUtils;

public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		System.out.println("filter destoroy");
	}

	@Override
	public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletrequest;
		HttpServletResponse response = (HttpServletResponse) servletresponse;
		String bbcunp = CookiesUtils.getCookiesByKey(request, "bbcunp");
		String bbcu = CookiesUtils.getCookiesByKey(request, "bbcu");
		if (StringUtils.isEmpty(bbcu) || StringUtils.isEmpty(bbcunp)) {
			response.sendRedirect(request.getContextPath()+"/login.action");
		} else if (bbcu.equals(PwdUtils.build(bbcunp)) && bbcunp.startsWith("20xbabaaiya@126.com0zsoftbeans")) {
			filterchain.doFilter(request,response);
		} else {
			response.sendRedirect(request.getContextPath()+"/login.action");
		}
	}

	@Override
	public void init(FilterConfig filterconfig) throws ServletException {
		System.out.println("filter init");
	}

}
